package http;

import myException.ServerConnectException;
import client.Server;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 模拟http请求
 */
public class RequestSender {

    public static ResponseParser responseParser = new ResponseParser();

    public static Response sendPostRequest(String apiUrl, String requestBody) throws ServerConnectException {
        try {
            Socket socket = Server.getServerConnectSocket();
            BufferedWriter requestWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
            StringBuilder requestContent = new StringBuilder();
            requestContent.append("POST " + apiUrl + " HTTP/1.1\r\n")
                    .append("Host: " + Server.HOST + "\r\n")
                    .append("Content-Type: application/json;charset=utf-8\r\n")
                    .append("Content-Length: " + requestBody.length() + "\r\n")
                    .append("\r\n")
                    .append(requestBody);
            //咱们这个应用发送的数据一般不会超过套接字缓冲区大小，因此就不做分包的设计了
            requestWriter.write(requestContent.toString());
            //超时、报IOException则重连服务器
            try {
                requestWriter.flush();
            } catch (Exception e) {
                Server.reConnect();
                throw new ServerConnectException();
            }
            return responseParser.parseResponseStream(socket.getInputStream());
        } catch (IOException e) {
            Server.reConnect();
            throw new ServerConnectException();
        }
    }


}
